<template>
  <div class="container">
    <div class="header">
      <div class="search">
        <van-icon name="search" color="rgb(153, 153, 153)" />
        <span class="placeholder">抢315元无门槛神劵</span>
      </div>
    </div>
    <div class="content">
      <ul class="cates" ref="cates">
        <li v-for="(val,inx) in cateList" :key="inx">
          <div :class="{current:currentCate===inx}">
            <span>{{val}}</span>
          </div>
        </li>
      </ul>
      <ul class="items" ref="items">
        <li
          v-for="(val,inx) in itemList"
          :key="inx"
          :style="{backgroundColor:val,height:'800px'}"
          ref="item"
        ></li>
      </ul>
    </div>
  </div>
</template>    
<style lang="less" scoped>
@import url("./index.less");
</style>
<script>
export default {
  name: "cate",
  data() {
    return {
      itemHeights: [],
      cateList: ["新品发布", "日用百货", "小米手机", "生活电器", "数据配件"],
      currentCate: 0,
      itemList: ["red", "gray", "black", "green", "pink"]
    };
  },
  mounted() {
    this.getItemHeights();
    this.$refs.items.addEventListener("scroll", this.windowScroll);
  },
  beforeDestroy() {
    this.$refs.items.removeEventListener("scroll", this.windowScroll);
  },
  methods: {
    windowScroll() {
      console.log(this.itemHeights);

      let scrollheight = this.$refs.items.scrollTop;
      for (let i = 0; i < this.itemHeights.length; i++) {
        if (this.itemHeights[i] > scrollheight) {
          this.currentCate = i;
          break;
        }
      }
    },
    getItemHeights() {
      this.$nextTick(() => {
        this.itemHeights = [];
        let items = this.$refs.item,
          sum = 0;
        for (let i = 0; i < items.length; i++) {
          sum += items[i].clientHeight;
          this.itemHeights.push(sum);
        }
      });
    }
  }
};
</script>